<template>
  <div>
    <a-form-model layout="horizontal" :model="form" v-bind="formItemLayout" :rules="rules" ref="formRef">
      <a-form-model-item label="字典标识" required prop="configKey">
        <a-input v-model="form.configKey" placeholder="请输入字典标识" :disabled="isEdit" />
      </a-form-model-item>
      <a-form-model-item label="字典详情" required prop="configValue">
        <JsonEditorVue
          :modelValue="form.configValue"
          @update:modelValue="handleConfigValueChange"
          :value="form.configValue"
          @input="handleConfigValueChange"
          :mode="'text'"
          :mainMenuBar="false"
          :navigationBar="false"
          :statusBar="false"
          :readOnly="false"
          :height="200"
          :indentation="2"
        />
        <pre class="placeholder-text" v-if="!form.configValue">
          {{ configValuePlaceholder }}
        </pre>
      </a-form-model-item>
      <a-form-model-item label="字典描述" prop="description">
        <a-textarea v-model="form.description" placeholder="请输入字典描述" style="height: 100px" />
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import VCA from '@vue/composition-api'
import JsonEditorVue from 'json-editor-vue'
import Vue from 'vue'
import { addDynamicConfig, updateDynamicConfig } from '@/api/dynamicConfig'

Vue.use(VCA)

const configValuePlaceholder = `Json格式，如：{ "accept": "通过"}`
const initFormData = () => ({
  configKey: '',
  configValue: '',
  description: '',
})
export default {
  name: 'AddAndEditForm',
  components: { JsonEditorVue },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 12 },
      },
      rules: {
        configKey: [{ required: true, message: '请输入字典标识', trigger: 'blur' }],
        configValue: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              // 如果值为空或未定义,则跳过验证
              if (!value) {
                callback()
                return
              }

              try {
                // 确保value是字符串类型
                if (typeof value !== 'string') {
                  callback(new Error('配置必须是JSON字符串格式'))
                  return
                }

                JSON.parse(value)

                callback()
              } catch (e) {
                callback(new Error('请输入有效的JSON格式'))
              }
            },
          },
        ],
      },
      form: initFormData(),
      configValuePlaceholder,
    }
  },
  // 使用Vue 2的生命周期钩子
  mounted() {
    // 初始化默认值
    this.initializeDefaultValues()
  },
  methods: {
    // 初始化默认值
    initializeDefaultValues(record) {
      if (!record) {
        this.form = initFormData()
        return
      }
      this.form = Object.assign({}, this.form, record)
    },
    // 处理钉钉配置变化
    handleConfigValueChange(value) {
      this.form.configValue = value
      console.log('handleConfigValueChange', value)
    },
    submitForm() {
      return new Promise((resolve, reject) => {
        this.$refs['formRef'].validate((valid) => {
          if (valid) {
            const api = this.isEdit ? updateDynamicConfig : addDynamicConfig
            api(this.form)
              .then((res) => {
                if (res.statusCode === 200) {
                  this.$message.success(this.isEdit ? '更新成功' : '添加成功')
                  resolve(res)
                } else {
                  this.$message.error(res.message)
                  reject(res)
                }
              })
              .catch((err) => {
                this.$message.error(err.message)
                reject(err)
              })
          } else {
            console.log('error submit!!')
            reject(new Error('表单验证失败'))
            return false
          }
        })
      })
    },
  },
}
</script>

<style lang="less" scoped>
.placeholder-text {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
  white-space: pre-line;
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
}
</style>
